<?php
// CLEAN - cleaning query
function clean($query) {
	if (get_magic_quotes_gpc()) {
		$query = stripslashes($query);
	}
	$query = mysql_real_escape_string($query);
	return $query;
}
function escape($str) {
	return mysql_escape_string(stripslashes($str));
}
function dbcontect(){
    $db = mysql_connect( DB_HOST, DB_USER, DB_PASS );
    mysql_select_db( DB_NAME ) or die( 'dberror' );
    mysql_query("SET NAMES utf8");
}
//$query = sprintf("select * from users where user='%s' and password='%s'",
//mysql_real_escape_string($user),
//mysql_real_escape_string($password));
function query_array( $field, $table, $where ) {
	$sSql = "SELECT $field FROM " . DB_PRIFIX . "$table WHERE $where";
	dbcontect();
	$result = mysql_query($sSql);
	$retrieve = array();
	while ($r = mysql_fetch_array( $result , MYSQL_ASSOC )) {$retrieve[] = $r;}
	return $retrieve;
}


function page( $p ){
    return ' LIMIT ' . ($p - 1) * DEFAULT_LIMIT . ', ' . DEFAULT_LIMIT;
}

function loreList( $page=1, $order ){ //UNIX_TIMESTAMP('YYYY-MM-DD HH:MM:SS'')
    $order = $order == 'right' ? 'lore_views DESC, lore_push DESC ' : 'lore_ctime DESC ' ;
    return query_array(
        'lore_id, FROM_UNIXTIME(lore_ctime,"%m %d %Y") as lore_ctime, lore_author, lore_desc',
        'main',
        'lore_pid=0 AND lore_aid=0 AND lore_status=1 order by ' . $order . page($page)   
    );
}
function loreView($loreId, $page=1 ){
	if( !is_numeric( $loreId ) ) return 0;
	return query_array(
        'lore_id, lore_pid, lore_aid, FROM_UNIXTIME(lore_ctime,"%m %d %Y") as lore_ctime, lore_author, lore_content',
        'main',
        '(lore_id='. intval($loreId) .' OR lore_pid='. intval($loreId) .') AND lore_status=1 ORDER BY lore_ctime ASC ' . page($page)   
    );
}
function loreSave($post){
	if(isset($post['r'])){
		$prev = explode('_', $post['r']);
		$pid = $prev[2]?$prev[2]:$prev[1];
		$aid = $prev[1];
	}
    $sSql = 'INSERT INTO ' .DB_NAME.'.'.DB_PRIFIX
		. 'main (`lore_pid`, `lore_aid`, `lore_author`, `lore_desc`, `lore_content`, `lore_ctime`, `lore_status`) '
		.'VALUES ('.intval( $pid ).','
		.intval( $aid ).',"'
		.escape( $post['userName'] ).'", "'
		.escape( get_str_length($post['content'])>WORD_LENGTH ? msubstr( $post['content'], 0, WORD_LENGTH ) : $post['content']).'", "'
		.escape( $post['content'] ).'", '.time().',	1);';

    dbcontect();
    if (  mysql_query( $sSql )) {
        return mysql_insert_id();
    }else{
        return $sSql;
    }
}